package chu.dejian.ui.fragmet;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

import chu.dejian.adapter.BLEDeviceListAdapter;

import com.sam.ble.base.application.BLEBRInterfApplication;
import com.sam.ble.base.fragment.BaseBLEClientFragment;
import com.sam.dejian.ble.fragment.WristMeasureDebugFragment;
import com.sam.dejian.ble.wrist_bp.WristBPDevice;
import com.sam.dejian.ble.wrist_bp.WristBPDeviceHelper;
import com.sam.blemodule.R;
import chu.dejian.conf.BLEPreference;

import com.sam.widget.headerBar.BaseHeaderView;
import com.sam.widget.headerBar.LeftImgTitleRightImgBar;

public class MeasureDeviceFragment extends BaseBLEClientFragment {
	private static MeasureDeviceFragment instance;
	public synchronized static MeasureDeviceFragment getInstance(){
		if(instance == null){
			instance = new MeasureDeviceFragment();
		}
		return instance;
	}

	enum DEVICE_STATE {UNSUPPORT_BT,DISCONNECT,SEARCHING,LIST_DEVICES, NO_DEVICES, FOUND_VALID_DEVICE,}

	private DEVICE_STATE deviceState;

	private LeftImgTitleRightImgBar header;
	private ListView deviceListView;
	private View scanProgress;
	private BLEDeviceListAdapter mLeDeviceListAdapter;
	private View disconnectView,connectedDeviceView,noDeviceView,unsupportBTView;
	private String deviceAddress;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_measure_device);
	}

	@Override
	public void findView() {
		header = (LeftImgTitleRightImgBar) findViewById(R.id.header);
		disconnectView = findViewById(R.id.disconnect_view);
		deviceListView = (ListView) findViewById(R.id.device_listview);
		scanProgress = findViewById(R.id.scan_progress);
		connectedDeviceView = findViewById(R.id.cnnected_device_view);
		noDeviceView = findViewById(R.id.no_device_view);
		unsupportBTView = findViewById(R.id.bt_unsupported);
	}

	public void initView() {
		header.setOnHeaderClickListener(onHeaderClickListener);
		mLeDeviceListAdapter = new BLEDeviceListAdapter(getActivity());
		deviceListView.setAdapter(mLeDeviceListAdapter);
		deviceListView.setOnItemClickListener(mDeviceClickListener);
		scanProgress.setOnClickListener(onClickListener);
		findViewById(R.id.to_connect_icon).setOnClickListener(onClickListener);
		findViewById(R.id.connected_device_icon).setOnClickListener(onClickListener);
		findViewById(R.id.no_device_icon).setOnClickListener(onClickListener);
	}

	@Override
	public void onResume() {
		super.onResume();
		// 首次进入直接开始扫描，如果是设备有问题返回来重新扫描则不需要自动扫描
		boolean isRescan = getArgumentBundle() != null && getArgumentBundle().getBoolean("isRescan");
		if(!isRescan) { // 如果测量过一次，存储在本地的设备信息就是有效的
			deviceAddress = BLEPreference.getInstance().getDeviceMac(null);
//			如果服务可用，再次进入测量页的时候就直接去测量页面吧，测量页面onResume会尝试重连，在这里重新扫描可能因为本来就连接了而扫不到我们的设备
			setDeviceState(DEVICE_STATE.DISCONNECT);
		} else {
			deviceAddress = null;
			setDeviceState(DEVICE_STATE.DISCONNECT);
		}
	}

	public synchronized void setDeviceState(DEVICE_STATE deviceState){
		if(this.deviceState == deviceState) return;
		this.deviceState = deviceState;
		disconnectView.setVisibility(View.GONE);
		scanProgress.setVisibility(View.GONE);
		deviceListView.setVisibility(View.GONE);
		connectedDeviceView.setVisibility(View.GONE);
		noDeviceView.setVisibility(View.GONE);
		unsupportBTView.setVisibility(View.GONE);

		if(deviceState == DEVICE_STATE.UNSUPPORT_BT) {
			unsupportBTView.setVisibility(View.VISIBLE);
			header.setRightVisibility(View.GONE);
		} else if(deviceState == DEVICE_STATE.DISCONNECT){
			disconnectView.setVisibility(View.VISIBLE);
		} else if(deviceState == DEVICE_STATE.SEARCHING){
			scanProgress.setVisibility(View.VISIBLE);
		} else if(deviceState == DEVICE_STATE.LIST_DEVICES){
			deviceListView.setVisibility(View.VISIBLE);
		} else if(deviceState == DEVICE_STATE.FOUND_VALID_DEVICE){
			connectedDeviceView.setVisibility(View.VISIBLE);
		} else if(deviceState == DEVICE_STATE.NO_DEVICES){
			noDeviceView.setVisibility(View.VISIBLE);
		}
	}



	private View.OnClickListener onClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			int i = v.getId();
			if (i == R.id.connected_device_icon) {
				connectToDevice(deviceAddress);

			} else if (i == R.id.no_device_icon) {
				setDeviceState(DEVICE_STATE.SEARCHING);
				startScanDevice();

			} else if (i == R.id.to_connect_icon) {
				if(deviceAddress == null) {
					setDeviceState(DEVICE_STATE.SEARCHING);
					startScanDevice();
				} else reconnectDevice();

			} else if (i == R.id.scan_progress) {
				stopScanDevice();

			}
		}
	};

	@Override
	public void onDeviceStopScanning() {
		super.onDeviceStopScanning();
		scanProgress.setVisibility(View.GONE);
	}

	private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
		public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
			BluetoothDevice device = mLeDeviceListAdapter.getItem(arg2);
			connectToDevice(device);
		}
	};

	@Override
	public void onBluetoothOpened() {
		super.onBluetoothOpened();
		verifyIfRequestPermission();
		setDeviceState(DEVICE_STATE.SEARCHING);
	}

	@Override
	public void onDeviceFounded(BluetoothDevice device) {
		super.onDeviceFounded(device);
		setDeviceState(DEVICE_STATE.LIST_DEVICES);
		if(device != null) mLeDeviceListAdapter.addDevice(device);
		mLeDeviceListAdapter.notifyDataSetChanged();
		if(WristBPDeviceHelper.getInstance().isLegitimate(device.getName())){
			deviceAddress = device.getAddress();
			setDeviceState(DEVICE_STATE.FOUND_VALID_DEVICE);
//			connectToDevice(device);
			stopScanDevice();
		}
	}

	@Override
	public void onDeviceStartScanning() {
		super.onDeviceStartScanning();
		verifyIfRequestPermission();
		deviceListView.setVisibility(View.VISIBLE);
		scanProgress.setVisibility(View.VISIBLE);
	}

	@Override
	public void onDeviceScanFinish() {
		super.onDeviceScanFinish();
		if(mLeDeviceListAdapter.getCount() == 0) setDeviceState(DEVICE_STATE.NO_DEVICES);
		scanProgress.setVisibility(View.GONE);
	}

	@Override
	public void onConnectDeviceSucceeded(String deviceAddress) {
		super.onConnectDeviceSucceeded(deviceAddress);
		this.deviceAddress = deviceAddress;
		Bundle bundle = MeasureFragment.getInstance().getArgumentBundle();
		bundle.putString("device_address", deviceAddress);
		replaceSelfWithFragment(MeasureFragment.getInstance());
	}

	@Override
	public void onConnectDeviceFailed(String deviceAddress) {
		super.onConnectDeviceFailed(deviceAddress);
		log("连接设备失败");
		setDeviceState(DEVICE_STATE.NO_DEVICES);
	}

	@Override
	public void onPause() {
		super.onPause();
		scanProgress.setVisibility(View.GONE);
	}

	@Override
	public void onServiceDiscoveredCallback(BluetoothDevice device, String serviceUUID, List<String> servicesCharas) {
		super.onServiceDiscoveredCallback(device, serviceUUID, servicesCharas);
		log("发现了服务:"+serviceUUID);
		if(serviceUUID.equals(WristBPDevice.UUID_STR_SERVICE)){
			log("终于发现了正确的服务:"+serviceUUID);
			bindReadCharacteristic(WristBPDevice.UUID_STR_SERVICE,WristBPDevice.UUID_STR_CONTROL_READ,WristBPDevice.UUID_STR_READ_CHARACTER_DESCRIPTOR);
		}
	}

	@Override
	public void onAccessCoarseLocationPermissionDenied() {
		super.onAccessCoarseLocationPermissionDenied();
		Toast.makeText(getActivity(), "位置访问权限被拒绝将无法搜索到ble设备", Toast.LENGTH_SHORT).show();
	}

	private BaseHeaderView.OnHeaderClickListener onHeaderClickListener = new BaseHeaderView.OnHeaderClickListener() {
		@Override
		public void onHeaderLeftClicked() {
			getActivity().finish();
		}

		@Override
		public void onHeaderRightClicked() {
			setDeviceState(DEVICE_STATE.SEARCHING);
			startScanDevice();
		}
	};

}
